import React from 'react'
import { connect } from 'dva'


import Title from '../../components/Title'
import AddressItem from '../../components/AddressItem'
import OrderListItem from '../../components/OrderListItem'

import './style.css'

/*
    整理出 order 对象

    1. 拿到用户的收件地址
    2. 渲染购物车商品详情
    3. 下单
        创建订单
        清空购物车  
*/

class CreateOrder extends React.Component {

    createOrtder = () => {
        /*
            1. 创建 order
            2. 查询所有 order
            3. 把 order id 传递到 orderInfo 页面
        */
        const { dispatch, order, history } = this.props
        new Promise((resolve, reject) => {
            dispatch({
                type: 'order/putOrder',
                payload: order.order,
                resolve, reject
            })
        })
        .then((id) => {
            // 3. 把 order id 传递到 orderInfo 页面
            history.push(`/orderInfo/${id}`)
        })
    }

    render() {
        const { order } = this.props
        console.log('order: ',order)
        return (
            <div className='createOrder'>
                <Title title='确认订单' />
                {
                    order.order && order.order.address && (
                        <AddressItem 
                            data={order.order.address}
                            editClick={this.updateAdd}
                            position='order'
                        />
                    )
                }
                {
                    order.order && (
                        <OrderListItem 
                            order={order.order}
                        />
                    )
                }
                <div className='createOrder-create' >
                    <div>   
                        <span>共2件, 合计: </span>
                        <span className='money'>¥: 99.99</span>
                    </div>
                    <button 
                        className='btn' 
                        onClick={this.createOrtder}
                    >下单</button>
                </div>

            </div>
        )
    }
}

const mapState = state => ({
    cart: state.cart,
    user: state.user,
    order: state.order
})

export default connect(mapState)(CreateOrder)
